home *** CD-ROM | disk | FTP | other *** search
- Path: news1.io.org!news
- From: ticica@io.org (Ivan)
- Newsgroups: comp.lang.c++
- Subject: What is wrong with this code?
- Date: 19 Mar 1996 00:57:27 GMT
- Organization: Internex Online (io.org), Toronto, Ontario, Canada
- Message-ID: <4il0pn$fp@news1.io.org>
- NNTP-Posting-Host: dyna-125.net7b.io.org
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.6
-
-
- Please, can someone tell me what's wrong with this program? It's driving
- me nuts. When I compile it with Borland C++ 3.1 I get null pointer
- assignment. With Watcom C++ 9.5 the last line (cout << a * 3) prints some
- junk. Thanks in advance.
-
- Ivan
- -------------------------------------------------------------------------
-
-
- #include <malloc.h>
- #include <stdlib.h>
- #include <iostream.h>
- #include <process.h>
- #include <stdarg.h>
- #include <string.h>
-
- typedef double datatype; // matrices and vectors will contain real numbers
-
- void memoryerror (void) {
- cout << "Not enough memory to allocate buffer\n";
- exit(1); /* terminate program if out of memory */
- }
-
- class vector {
- private:
- int dim; // dimension of vector
- datatype *data; // the contents of vector (dynamicly
- // allocated)
- char *name; // Just an ID for a vector
- public:
- vector (char* , int , ...); // parameters are the
- // dimension and values
- vector (void); // sets dim to -1 (for later
- // interactive input).
- ~vector (void); // destructor
-
- friend ostream &operator << (ostream &, const vector &);
-
- friend vector operator *(vector &, datatype);
-
- };
-
- vector::vector (char *newname, int dimension, ...)
- {
- dim = dimension;
- if (!(data = new datatype[dim]))
- memoryerror();
-
- if (!(name = new char[strlen(newname)+1]))
- memoryerror();
- strcpy (name, newname);
-
- va_list ap;
- float arg;
- va_start(ap, dimension);
- for (int i=0;i<dimension;i++) {
- data[i] = va_arg(ap, datatype);
- }
- va_end(ap);
- }
-
- vector::~vector (void) {
- if (data) delete data;
- if (name) delete name;
- }
-
- vector::vector (void)
- {
- dim = -1;
- data = NULL;
- name = new char[8];
- strcpy (name, "unnamed");
- }
-
- ostream &operator << (ostream &output, const vector &vec)
- {
- output << "\nVector '" << vec.name << "' is of dimension " << vec.dim;
- output << " and it's parameters are:\n";
- for (int i = 0; i < vec.dim; i++) {
- output << '\n' << vec.name << "[" << i+1 << "] = " << vec.data[i];
- }
-
- return output;
- }
-
- vector operator * (vector &vec, datatype a)
- {
- vector vecret;
- vecret.dim = vec.dim;
- if (!(vecret.data = new datatype[vec.dim]))
- memoryerror();
-
- for (int i=0;i<vec.dim;i++) { // copy all the values
- vecret.data[i] = vec.data[i] * a;
- }
- return vecret;
- }
-
- void main(void)
- {
- vector a("first", 4, 1.0, 2.0, 3.0, 4.0);
- vector b("second", 2, 1.1, 1.2);
- cout << a;
- cout << b;
- cout << a * 3;
- }
-
-
-
-
-
-
-
-